import os
import sys
import traceback

from PySide6.QtCore import Qt, QSize
from PySide6.QtGui import QDragEnterEvent, QDropEvent, QFont
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget, QPushButton, QFileDialog, QHBoxLayout, QSizePolicy, \
    QMessageBox, QListWidget, QListWidgetItem, QLayout

from analysis import analysis
from analysis import __version__

# global variables
app_types = {"xjcz": "xjcz", "xj_upload": "upload", "xjcz_evidence": "evidence", "evidence旧模式": "evidence旧模式"}
app_type_items = {"xjcz": QListWidgetItem("xjcz"), "upload": QListWidgetItem("xj_upload"), "evidence": QListWidgetItem("xjcz_evidence"),
                  "evidence旧模式": QListWidgetItem("evidence旧模式")}


def get_app_name_by_path(file_path):
    file_name = file_path.split("\\")[-1].split("/")[-1]
    if file_name.startswith("xj_upload"):
        return app_type_items["upload"]
    elif file_name.startswith("xjcz_light_evidence"):
        return app_type_items["evidence"]
    elif file_name.startswith("xjcz"):
        return app_type_items["xjcz"]
    else:
        return None


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # 日志文件路径
        self.log_file_path = None
        # 设置窗口
        self.setWindowTitle(f"{__version__.__title__} v{__version__.__version__}")
        self.setMinimumSize(QSize(450, 300))
        # 设置窗口字体大小
        font = QFont()
        font.setPointSize(12)
        bold_font = QFont()
        bold_font.setPointSize(12)
        bold_font.bold()
        tiny_font = QFont()
        tiny_font.setPointSize(10)
        self.setFont(font)

        # 创建程序类型列表
        self.app_type_list = QListWidget()
        self.app_type_list.setFixedWidth(122)
        self.app_type_list.setFont(bold_font)
        self.app_type_list.setStyleSheet("""
        QListWidget { 
            background-color: rgba(0, 0, 0, 0);
            border: 0; 
        } 
        QListWidget::item:selected { 
            background-color: #00b7c3; 
        }
        """)
        for app_type, item in app_type_items.items():
            self.app_type_list.addItem(item)
        self.app_type_list.item(0).setSelected(True)

        # 创建拖拽区域标签
        self.drag_label = QLabel(self)
        self.drag_label.setAlignment(Qt.AlignCenter)
        self.drag_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.drag_label.setText("拖拽文件到这里")
        self.drag_label.setStyleSheet("QLabel { background-color: white; border: 1px solid gray; }")
        self.setAcceptDrops(True)

        # 创建用于显示文件路径的标签
        self.file_path_label = QLabel(self)
        self.file_path_label.setAlignment(Qt.AlignCenter)
        self.file_path_label.setFont(tiny_font)
        self.file_path_label.setWordWrap(True)
        self.file_path_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        # 调整标签的大小以适应文本
        self.file_path_label.adjustSize()

        # 创建按钮
        self.generate_btn = QPushButton("生成解析报告", self)
        self.generate_btn.clicked.connect(self.process_start)
        # self.generate_btn.setFixedWidth(300)
        self.generate_btn.setFont(bold_font)
        self.generate_btn.setStyleSheet("""
        QPushButton {
            padding: 10px;
            margin: 0 auto;
        }
        """)

        # 创建控件的垂直布局
        ctrl_layout = QVBoxLayout()
        ctrl_layout.addWidget(self.drag_label)
        ctrl_layout.addWidget(self.file_path_label)
        ctrl_layout.addWidget(self.generate_btn)
        ctrl_layout.setSizeConstraint(QLayout.SetDefaultConstraint)

        # 创建水平布局
        layout = QHBoxLayout()
        layout.addWidget(self.app_type_list)
        layout.addLayout(ctrl_layout)

        # 创建主窗口的中心部件并设置布局
        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

        # 连接点击事件到打开文件浏览器函数
        self.drag_label.mousePressEvent = self.open_file_dialog

    def dragEnterEvent(self, event: QDragEnterEvent):
        # 检查拖拽事件中的数据类型
        if event.mimeData().hasUrls():
            event.acceptProposedAction()

    def dropEvent(self, event: QDropEvent):
        # 获取拖拽的文件路径
        urls = event.mimeData().urls()
        file_paths = [url.toLocalFile() for url in urls]

        # 更新文件路径标签
        self.file_path_label.setText("\n".join(file_paths))
        self.log_file_path = file_paths[0]
        current_file_mode = get_app_name_by_path(self.log_file_path)
        if current_file_mode:
            self.app_type_list.setCurrentItem(current_file_mode)

    def open_file_dialog(self, event):
        # 打开文件对话框
        file_dialog = QFileDialog()
        file_path, _ = file_dialog.getOpenFileName(self, "选择文件")
        if file_path:
            # 更新文件路径标签
            self.file_path_label.setText(file_path)
            self.log_file_path = file_path
            current_file_mode = get_app_name_by_path(self.log_file_path)
            if current_file_mode:
                self.app_type_list.setCurrentItem(current_file_mode)

    def process_start(self):
        message_box = QMessageBox()
        message_box.setWindowTitle("提示")

        # 获取用户选择
        item = self.app_type_list.currentItem()
        out_type = "excel"

        # 未选中程序类型
        if item is None:
            message_box.setText("未选择程序类型\n请选择程序的类型！")
            message_box.exec()
            return

        # 未选中日志文件
        if self.log_file_path is None:
            message_box.setText("未选择文件\n请选择要解析的日志文件！")
            message_box.exec()
            return

        # 获取选中的程序类型
        app_type = app_types[item.text()]

        # 开始处理
        try:
            result_dest = analysis.process(app=app_type, path=self.log_file_path, out=out_type)
            # 打开解析报告所在的目录
            os.startfile(os.path.abspath(result_dest))
        except PermissionError:
            error_box = QMessageBox()
            error_box.setWindowTitle("错误")
            error_box.setText("没有生成文件的权限\n请检查是否打开了同名文件！")
            error_box.exec()
            return
        except Exception:
            error_box = QMessageBox()
            error_box.setWindowTitle("错误")
            error_box.setText(f"程序执行过程中发生异常：\n\n{traceback.format_exc()}")
            error_box.exec()
            return


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())
